package com.hu.hutool.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.hu.hutool.common.CssConstantProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Oss 文件上传
 * @Author CazCen
 * @Date 2022/1/16 13:03
 */
public class OssFileUploadUtil {

    /**
     * oss 文件上传
     * @param file
     * @return String 返回 oss 下载url
     */
    public static String upLoadFile(MultipartFile file) throws OSSException, ClientException, IOException {

        String accessKeyId = CssConstantProperties.ACCESS_KEY_ID;

        String accessKeySecret = CssConstantProperties.ACCESS_KEY_SECRET;

        String endPoint = CssConstantProperties.END_POINT;

        String bucketName = CssConstantProperties.BUCKET_NAME;

        String bucketHost = CssConstantProperties.BUCKET_HOST;


        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        if(!ossClient.doesBucketExist(bucketName)){
            //创建bucket
            ossClient.createBucket(bucketName);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        //获取文件后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String dateStr = DateUtil.date().toString("yyyy-MM-dd");
        String fileName = dateStr +"-"+ UUID.randomUUID().toString().replace("-","") + suffix;

        ossClient.putObject(bucketName, fileName, file.getInputStream());
        String url = bucketHost + "/" + fileName;

        ossClient.shutdown();

        return url;
    }

}
